#pragma once

#include "cmd.h"
#include <dirent.h>
#include <sys/stat.h>
#include <unistd.h>

extern std::string usingdb;
//create database <dbname>
//create table <table-name> (<column> <type> [primary], …)
class Create{
private:
    std::vector<std::string> cmd;
public:
    Create(std::vector<std::string> a) : cmd(a){}
    void execute(){
        if(cmd.size() < 3) {
            std::cout << "No such command" <<std::endl;
            return;
        }
        cmdToUper(cmd[1]);

        if(cmd[1] == "DATABASE"){
            std::string pathname = "../data";
            int ret = 0;
            DIR * mydir = nullptr;
            mydir = opendir(pathname.c_str()); 
            if(mydir == nullptr)//data文件创建
            {
                ret = mkdir(pathname.c_str(),0755);
                if(ret!=0) std::cout<<"mkdir fialed"<<std::endl;
            }
            closedir(mydir);

            pathname += '/';
            pathname += cmd[2];//名字未作限制
            mydir = opendir(pathname.c_str()); //数据库文件创建
            if(mydir == nullptr)
            {
                ret = mkdir(pathname.c_str(),0755);
                if(ret!=0) std::cout<<"mkdir fialed"<<std::endl;
                else std::cout<<"create success"<<std::endl;
            }else{
                std::cout<<"Can't create database '"<< cmd[2] << "'; database exists" <<std::endl;;
            }
            closedir(mydir);

        }
        else if(cmd[1] == "TABLE"){
            if(usingdb == " ") {
                std::cout<<"No database selected"<<std::endl;
                return;
            }
            std::string pathname = "../data/";
            pathname += usingdb;
            pathname += '/';
            pathname += cmd[2];//名字未作限制
            pathname += ".dat";
            int ret = 0;
            FILE * myfl = nullptr;
            if(access(pathname.c_str(),F_OK) == 0){
                std::cout<<"Can't create table '"<< cmd[2] << "'; table exists" <<std::endl;;
            }else{
                myfl = fopen(pathname.c_str(),"a+"); //表文件创建
                if(myfl = nullptr) std::cout<<"create fialed"<<std::endl;
                else std::cout<<"create success"<<std::endl;
                fclose(myfl);
            }
            
            
            
        }

        else{
            std::cout << "No such command" <<std::endl;
        }
    }
};